package ioc

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/spf13/viper"
)

// S3Config S3服务配置结构
type S3Config struct {
	Region     string `yaml:"region"`
	Endpoint   string `yaml:"endpoint"`
	AccessKey  string `mapstructure:"access_key"`
	SecretKey  string `mapstructure:"secret_key"`
	DisableSSL bool   `yaml:"disable_ssl"`
}

// NewS3 创建并返回S3客户端实例
func NewS3() *s3.S3 {
	region := viper.GetString("s3.region")
	endpoint := viper.GetString("s3.endpoint")
	accessKey := viper.GetString("s3.access_key")
	secretKey := viper.GetString("s3.secret_key")

	// 阿里云OSS专用配置
	if region == "" {
		region = "cn-beijing"
	}
	if endpoint == "" {
		endpoint = "https://oss-cn-beijing.aliyuncs.com"
	}

	// 确保 endpoint 包含协议
	if !hasProtocol(endpoint) {
		endpoint = "https://" + endpoint
	}

	awsCfg := &aws.Config{
		Region: aws.String(region),
		Credentials: credentials.NewStaticCredentials(
			accessKey,
			secretKey,
			"",
		),
		Endpoint: aws.String(endpoint),
		// 关键：阿里云OSS必须使用虚拟托管式访问
		S3ForcePathStyle: aws.Bool(false),
	}

	sess, err := session.NewSession(awsCfg)
	if err != nil {
		panic(fmt.Sprintf("Failed to create AWS session: %v", err))
	}

	return s3.New(sess)
}

func hasProtocol(endpoint string) bool {
	return len(endpoint) > 7 && (endpoint[0:7] == "http://" || endpoint[0:8] == "https://")
}
